from flask import  Flask
from flask_cors import  CORS

from flask import request,jsonify
import json
import datetime
import random
from db import db

app = Flask(__name__)

CORS(app)

app.config['JSON_AS_ASCII'] = False




"""

电商系统

"""

#模拟三方支付回调接口
@app.route('/payment/')
def payment():
    #流水号  模拟 现在时间加随机6位数
    transaction = str(datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d"))+str(random.randint(100000,999999))
    return jsonify({"code":200,'transaction':transaction})

#回单后修改状态
@app.route("/huipay/")
def huipay():
    transaction = request.args.get('transaction')
    order_on = request.args.get('order_on')
    #根据订单号查询用户id 商品id修改支付状态
    sql1="select * from dorders where dorder_on='%s'"%(order_on)
    res1 = db.find_one(sql1)
    # 修改订单为为支付状态 以及 写入回单号
    sql2 = "update dorders set dstatus=2,dtransaction='%s' where duserid=%d and dgoodsid=%d"%(transaction,res1['duserid'],res1['dgoodsid'])
    db.insert(sql2)
    return jsonify({"code":200,'mas':'支付成功，正在返回商品页'})


#生成订单
@app.route('/createorder/')
def createorder():
    #接收用户id和商品id
    userid =int(request.args.get('userid'))
    goodsid = int(request.args.get('goodsid'))

    #根据用户id 查看用户有没有生成该商品的订单
    sql = "select * from dorders where duserid=%d and dgoodsid=%d"%(userid,goodsid)
    res = db.find_one(sql)

    #时间
    stime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%m:%S")

    #订单号
    order_on = str(datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d"))+str(userid)+str(random.randint(10000,99999))

    # #没有添加订单 有直接让用户支付
    if res:
        
        return jsonify({'code':20020,'mas':'您已经有该订单请支付'})

        #测试使用  现在没用
        # transaction = payment(order_on)
        # #修改订单为为支付状态 以及 写入回单号
        # sql2 = "update dorders set dstatus=2,dtransaction='%s' where duserid=%d and dgoodsid=%d"%(transaction,userid,goodsid)
        # db.insert(sql2)

    else:
        #生成订单
        sql1 = "insert into dorders(duserid,dgoodsid,dstime,dorder_on,dstatus) values(%d,%d,'%s','%s',1)"%(userid,goodsid,stime,order_on)
        db.insert(sql1)
        return jsonify({'code':200,'url':'/dpayment','order_on':order_on})




#获取商品列表
@app.route("/getgoods/")
def getgoods():
    sql = "select * from dgoods"
    res = db.find_all(sql)
    return jsonify({'code':200,'list':res})



#后台发货
@app.route("/delivers/")
def deliver():
    #查所有支付成功订单点击发货
    
    sql = "select dg.name,al.* from (select du.name,do.* from dorders as do left join duser as du on do.duserid=du.id where dstatus=2) as al inner join dgoods as dg on al.dgoodsid=dg.id"
    res = db.find_all(sql)
    return jsonify({'code':200,'list':res})













if __name__ == '__main__':
    app.run(debug=True,host='127.0.0.1',port=5000)















